package com.example.demo.service.impl;

import com.example.demo.client.evt.sysbasequery.TrusteeshipOfUserEvt;
import com.example.demo.client.vm.sysbasequery.UserTrusteeshipVm;
import com.example.demo.enums.YesOrNo;
import com.example.demo.mapper.UserTrusteeshipMapper;
import com.example.demo.service.BaseService;
import com.example.demo.service.UserTrusteeshipService;
import com.example.demo.web.rest.evt.IdEvt;
import com.example.demo.web.rest.evt.SaveUserTrusteeshipEvt;
import com.example.demo.web.rest.evt.UserTrusteeshipEvt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author zhengmf
 * @Date 2019/1/3  11:02
 */
@Service
@Transactional
public class UserTrusteeshipServiceImpl extends BaseService implements UserTrusteeshipService {
    @Autowired
    private UserTrusteeshipMapper userTrusteeshipMapper;
    @Override
    public Long saveUserTrusteeship(SaveUserTrusteeshipEvt evt) {
        Long userTrusId = null;
        UserTrusteeshipEvt userTrusteeship = new UserTrusteeshipEvt();
        BeanUtils.copyProperties(evt, userTrusteeship);
        userTrusteeship.setStatus(YesOrNo.Y.name());
        List<Long> trusIdList = evt.getTrusId();
        userTrusteeship.setUserId(getCurrentUserId());
        if(evt.getId() == null) {//新增
            for (Long trusId : trusIdList) {
                userTrusteeship.setUserTrusId(trusId);
                Long checkId = checked(userTrusteeship);
                if (checkId != null) {
                    userTrusId = checkId;
                    break;
                }
                userTrusteeshipMapper.addUserTrusteeship(userTrusteeship);
                logger.info("增加用户托管ID为:"+userTrusteeship.getId());
            }
            return userTrusId;
        }else {
            //编辑的旧记录   根据id获取被托管人的id
            IdEvt idEvt = new IdEvt();
            idEvt.setId(userTrusteeship.getId());
            UserTrusteeshipVm oldTrusteeship = baseQueryClient.getTrusteeshipById(idEvt).getBody();
            //获取当前编辑记录的原被托管人id
            Long oldTrusId = oldTrusteeship.getUserTrusId();
            String oldTrusType = oldTrusteeship.getTrusType();
            //若原代理人或托管类型不变，更新旧记录，否则删除旧记录,true:删除旧记录
            boolean flag = true;
            for (Long trusId : trusIdList) {
                userTrusteeship.setUserTrusId(trusId);
                //没有编辑直接保存
                if (trusIdList.size() == 1 && oldTrusId.equals(userTrusteeship.getUserTrusId())
                    && oldTrusType.equals(userTrusteeship.getTrusType())
                    && oldTrusteeship.getStartTime().equals(userTrusteeship.getStartTime())
                    && oldTrusteeship.getEndTime().equals(userTrusteeship.getEndTime())) {
                    continue;
                }
                //代理人不变且托管类型不变，更新，不删除旧记录，否则插入新记录，删除旧记录
                if (oldTrusId.equals(userTrusteeship.getUserTrusId())
                    && oldTrusType.equals(userTrusteeship.getTrusType())) {
                    flag = false;
                }
                //代理人变或托管类型变，插入新纪录，删除旧记录
                if (!oldTrusId.equals(userTrusteeship.getUserTrusId())
                    || !oldTrusType.equals(userTrusteeship.getTrusType())) {
                    //重复托管的代理人id
                    Long checkId = checked(userTrusteeship);
                    if (checkId == null) {
                        userTrusteeshipMapper.addUserTrusteeship(userTrusteeship);
                        //若原代理人或托管类型不变，更新旧记录，否则删除旧记录
                        if (flag) {
                            userTrusteeshipMapper.delUserTrusteeship(oldTrusteeship.getId());
                        }
                    } else {
                        userTrusId = checkId;
                        break;
                    }
                    //代理人不变且托管类型不变，改变时间的情况更新记录，包括追加代理人中旧代理人的循环中更新旧记录的情况
                } else {
                    Long checkId = checked(userTrusteeship);
                    int repeatCount = repeatCount(userTrusteeship);
                    if (checkId == null || repeatCount < 2) {
                        userTrusteeshipMapper.updateUserTrusteeship(userTrusteeship);
                        continue;
                    }
                    if (repeatCount > 2 ) {
                        userTrusId = checkId;
                        break;
                    }
                }
            }
            return userTrusId;
        }
    }

    /**
     *  检出是否有重复托管，返回null可新增，否则返回重复托管的被托管人id
     * @param userTrusteeship
     * @return
     */
    private Long checked(UserTrusteeshipEvt userTrusteeship) {
        Long trusId = null;
        TrusteeshipOfUserEvt evt = new TrusteeshipOfUserEvt();
        BeanUtils.copyProperties(userTrusteeship, evt);
        List<UserTrusteeshipVm> userTrusteeshipOfUser = baseQueryClient.getTrusteeshipOfUser(evt).getBody();
        if (userTrusteeshipOfUser.size() == 0) {
            return trusId;
        } else {
            int count = 0;
            for (UserTrusteeshipVm vm : userTrusteeshipOfUser) {
                //o.start<end<o.end 结束点有重合
                if (vm.getStartTime().getTime()-userTrusteeship.getEndTime().getTime()<=0
                    && userTrusteeship.getEndTime().getTime()-vm.getEndTime().getTime()<=0) {
                    trusId = userTrusteeship.getUserTrusId();
                    break;
                }
                //o.start<start<o.end 开始点有重合
                if (vm.getStartTime().getTime()-userTrusteeship.getStartTime().getTime()<=0
                    && userTrusteeship.getStartTime().getTime()-vm.getEndTime().getTime()<=0) {
                    trusId = userTrusteeship.getUserTrusId();
                    break;
                }
                //o.start<start && end<o.end 开始点和结束点都重合
                if (vm.getStartTime().getTime()-userTrusteeship.getStartTime().getTime()<=0
                    && userTrusteeship.getEndTime().getTime()-vm.getEndTime().getTime()<=0) {
                    trusId = userTrusteeship.getUserTrusId();
                    break;
                }
                //start<o.start && end > o.end 跨点
                if (userTrusteeship.getStartTime().getTime()-vm.getStartTime().getTime()<=0
                    && userTrusteeship.getEndTime().getTime()-vm.getEndTime().getTime()>=0) {
                    count++;
                    if (count > 0) {
                        trusId = userTrusteeship.getUserTrusId();
                        break;
                    }
                }
            }
            return trusId;
        }
    }
    /**
     * 获得数据库中与传入的记录有重合的记录条数
     * @param userTrusteeship
     * @return
     */
    private Integer repeatCount(UserTrusteeshipEvt userTrusteeship) {
        TrusteeshipOfUserEvt evt = new TrusteeshipOfUserEvt();
        BeanUtils.copyProperties(userTrusteeship, evt);
        List<UserTrusteeshipVm> userTrusteeshipOfUser = baseQueryClient.getTrusteeshipOfUser(evt).getBody();
        int count = 0;
        if (userTrusteeshipOfUser.size() == 0) {
            return count;
        } else {
            for (UserTrusteeshipVm vm : userTrusteeshipOfUser) {
                //o.start<end<o.end 结束点有重合
                if (vm.getStartTime().getTime()-userTrusteeship.getEndTime().getTime()<=0
                    && userTrusteeship.getEndTime().getTime()-vm.getEndTime().getTime()<=0) {
                    count++;
                    continue;
                }
                //o.start<start<o.end 开始点有重合
                if (vm.getStartTime().getTime()-userTrusteeship.getStartTime().getTime()<=0
                    && userTrusteeship.getStartTime().getTime()-vm.getEndTime().getTime()<=0) {
                    count++;
                    continue;
                }
                //o.start<start && end<o.end 开始点和结束点都重合
                if (vm.getStartTime().getTime()-userTrusteeship.getStartTime().getTime()<=0
                    && userTrusteeship.getEndTime().getTime()-vm.getEndTime().getTime()<=0) {
                    count++;
                    continue;
                }
                //start<o.start && end > o.end 跨点
                if (userTrusteeship.getStartTime().getTime()-vm.getStartTime().getTime()<=0
                    && userTrusteeship.getEndTime().getTime()-vm.getEndTime().getTime()>=0) {
                    count++;
                }
            }
            return count;
        }
    }

    @Override
    public void updateStatus(Long id) {
        userTrusteeshipMapper.updateStatusById(id);
    }


}
